import axios from "axios";
//引入原生node的字符串查询方法
import qsString from "querystring";
//引入封装好的仓库文件
import store from "../store";

let baseUrl = "/api";

//创建请求拦截器
axios.interceptors.request.use((req) => {
  // console.log(req,'4444444444')
  if (req.url != "/api/login") {
    req.headers.authorization = store.getters.getUser.token;
  }
  return req;
});
//响应拦截
axios.interceptors.response.use((res) => {
  return res.data;
});

/* 
独立封装get 方法
Params ===== url  指调取的接口地址
Params ===== params 参数
*/
export const get = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .get(baseUrl + url, {
        params,
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

/* 
独立封装post 方法
Params ===== url  指调取的接口地址
Params ===== params 参数
Params ===== isFile 是否含有文件
*/

export const post = (url, params = {}, isFile = false) => {
  let data = null;
  //有文件的传参逻辑
  if (isFile) {
    data = new FormData();
    for (let i in params) {
      data.append(i, params[i]);
    }
  } else {
    data = qsString.stringify(params);
  }
  return new Promise((resolve, reject) => {
    axios
      .post(baseUrl + url, data)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
